package com.qc31.monitorlib.ui.adapter

import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.qc31.baselib.utils.GsonUtil
import com.qc31.comlib.UrlUtil
import com.qc31.comlib.entity.RealVideoInfo
import com.qc31.comlib.entity.VideoState
import com.qc31.comlib.net.ServiceHelper
import com.qc31.monitorlib.R
import com.qc31.monitorlib.ui.video.view.RealVideo
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import java.net.URLEncoder
import java.util.*

/** @Author Jasper @Time 2020/9/17 @Desc */
class RealVideoAdapter(private val userId: String, var carId: String) :
    BaseQuickAdapter<RealVideoInfo, BaseViewHolder>(R.layout.item_real_video) {
    var fullKey = ""

    override fun convert(holder: BaseViewHolder, item: RealVideoInfo) {
        item.let {
            val realVideo: RealVideo = holder.getView(R.id.mRealVideo)
            val toast: TextView = holder.getView(R.id.tv_video_toast)
            val position: Int = holder.layoutPosition

            initVideo(it, realVideo, toast, position)
        }
    }

    private fun initVideo(
        item: RealVideoInfo,
        realVideo: RealVideo,
        toast: TextView,
        position: Int
    ) {
        realVideo.setIsTouchWiget(false)
        realVideo.backButton.visibility = View.GONE
        if (item.toast.isNotEmpty()) {
            toast.visibility = View.VISIBLE
            toast.text = item.toast
            realVideo.startButton.visibility = View.GONE
            return
        }
        realVideo.playPosition = position
        realVideo.isRotateViewAuto = true
        realVideo.isLockLand = true
        realVideo.isShowFullAnimation = true
        realVideo.setIsTouchWigetFull(false)
        toast.visibility = View.GONE
        realVideo.setIndex(position)
        realVideo.attachObserver()

        realVideo.fullscreenButton.setOnClickListener {
            fullKey = realVideo.getKey()
            realVideo.startWindowFullscreen(context, actionBar = false, statusBar = true)
        }

        realVideo.setOnStreamChangeListener(object : RealVideo.OnStreamChangeListener {
            override fun onChange(isMainStream: Boolean) {
                changePlayState(item, realVideo, false)
            }
        })

        realVideo.startButton.setOnClickListener {
            if (!realVideo.isInPlayingState) {
                startPlay(item, realVideo)
            } else {
                realVideo.release()

                changePlayState(item, realVideo, true)
            }
        }
        realVideo.setVideoAllCallBack(object : GSYSampleCallBack() {
            override fun onPlayError(url: String?, vararg objects: Any?) {
                super.onPlayError(url, *objects)
                realVideo.release()
                realVideo.startButton.visibility = View.GONE
                getErrorState(item, toast, realVideo)
            }
        })

        if (!realVideo.isInPlayingState) {
            startPlay(item, realVideo)
        }
    }

    /** 播放视频 */
    private fun startPlay(item: RealVideoInfo, realVideo: RealVideo) {
        realVideo.setUp(
            getPlayParams(item),
            false,
            context.getString(R.string.desc_video_pass) + item.videoPass
        )
        realVideo.startPlayLogic()
    }

    /** 请求失败原因 */
    private fun getErrorState(entity: RealVideoInfo, toast: TextView, realVideo: RealVideo) {
        realVideo.showProgress(true)
        ServiceHelper.getRepository().getVideoState(getVideoState(entity.uuid)).subscribe({
            val result = GsonUtil.formObject<VideoState?>(it)
            realVideo.showProgress(false)
            if (result==null){
                toast.text = UrlUtil.getToastMap()["88"]
            }else{
                toast.text = UrlUtil.getToastMap()[result.state]
            }

            toast.visibility = View.VISIBLE
        }, {
            realVideo.showProgress(false)
            if (it.message == context.getString(R.string.net_error_1006)) {
                toast.text = UrlUtil.getToastMap()["66"]
            }
            toast.visibility = View.VISIBLE
        })
    }

    /** 关闭播放 改变码流 */
    private fun changePlayState(
        item: RealVideoInfo,
        realVideo: RealVideo,
        isClose: Boolean
    ) {
        ServiceHelper.getRepository().getVideoState(getVideoParams(item, isClose)).subscribe({
            val result = GsonUtil.formObject<VideoState>(it)
            if (result.state == "0") {
                if (!isClose) {
                    if (item.videoStream == "1")
                        item.videoStream = "0"
                    else
                        item.videoStream = "1"
                }
                return@subscribe
            }
            realVideo.showProgress(false)
        }, {
            realVideo.showProgress(false)
        })
    }

    /** 获取参数拼接 */
    private fun getVideoParams(item: RealVideoInfo, isClose: Boolean): String {
        return if (isClose) {
            "httpflv.rctr.close.${item.uuid}"
        } else {
            "httpflv.rctr.switch.${item.uuid}.${if (item.videoStream == "1") "0" else "1"}"
        }
    }

    /** 获取播放视频参数 */
    private fun getPlayParams(entity: RealVideoInfo): String {
        val uuid = UUID.randomUUID().toString()
        entity.uuid = uuid
        return "${UrlUtil.mVideoHost}/httpflv.rplay.$uuid.${
            URLEncoder.encode(userId, "utf-8")
        }.$carId.${entity.videoPass}.0.${entity.videoStream}"
    }

    /** 播放状态 */
    private fun getVideoState(uuid: String): String {
        return "httpflv.state.$uuid"
    }

}